package com.example.lsrsbackend.controller;


import com.example.lsrsbackend.model.DTO.ReservationRequest;
import com.example.lsrsbackend.model.view.ReservationVO;
import com.example.lsrsbackend.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/reservations")
public class ReservationController {

    @Autowired
    private ReservationService reservationService;


    // 获取预约列表
    @GetMapping("/all") //获取信息有问题 ，感觉向字段没映射到数据库
    public ResponseEntity<List<ReservationVO>> getAllReservations() {
        List<ReservationVO> reservations = reservationService.getAllReservations();
        return ResponseEntity.ok(reservations);
    }
    //TODO 添加预约记录
    @PostMapping("/reserve")
    public ResponseEntity<Map<String, Object>> addReservation(@RequestBody ReservationRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String reservationId = reservationService.reserveSeat(request);
            response.put("success", true);
            response.put("message", "预约成功");
            response.put("reservationId", reservationId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }


    // 取消/删除预约记录
    @PostMapping("/{reservationId}/cancel")
    public ResponseEntity<Map<String, Object>> cancelReservation(
            @PathVariable String reservationId,
            @RequestHeader(required = false) String userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 如果userId为空，则从预约记录中获取用户名
            if (userId == null || userId.trim().isEmpty()) {
                reservationService.cancelReservationWithoutUserCheck(reservationId);
            } else {
                reservationService.cancelReservation(reservationId, userId);
            }

            response.put("success", true);
            response.put("message", "预约取消成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
